﻿using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections;
using System.Configuration;

namespace ProcessesSMS
{
	/// <summary>
	/// Summary description for.
	/// Project name: SMS_xoso
	/// channel: n/a
	/// command code: HN X Y
	/// created: 01/09/09 .
	/// Writer : THINHTD + Tuanbc
	/// Company: HANEL TELECOM
	/// </summary>

	public class XOSO
	{
		#region Declare
		private SMS_MO WMO;
		private SMS_MT WMT;
		//private SMS_LIST WML;
		ArrayList arr = new ArrayList();
		//DateTime datetime;
		public XOSO(SMS_MO MO)
		{
			WMO = MO;
		}

		public XOSO()
		{
		}
		#endregion
		#region Method
		public void run()
		{
			XOSO_WAIT xs_wait = new XOSO_WAIT();
			WMT = new SMS_MT(WMO);			
			string tmpMsg = WMO.Message.Substring(WMO.CommandCode.Length).Trim().Replace("  ", " ").Replace("  ", " ");
			tmpMsg = tmpMsg.Replace("  ", " ").Trim().ToUpper();
			string[] msg = tmpMsg.Split(new char[] { ' ' });
            if ((WMO.ServiceID.Replace("04", "") == "7162") || (WMO.ServiceID.Replace("04", "") == "7262") || (WMO.ServiceID.Replace("04", "") == "7362") || (WMO.ServiceID.Replace("04", "") == "7462"))
			{				
				if(tmpMsg.Trim()=="")//lay ket qua moi nhat
				{
					if((DateTime.Now.Hour>=19) && (CheckCurrentResult()==false))//Neu nhan sau 7h ma chua co ket moi nhat thi o che do cho
					{
                        string msgCHO = "7x62 xac nhan thong tin ban chuyen toi tong dai.Chung toi se gui toi ban ket qua XSTD ngay khi qua trinh quay so hoan tat";
                        WMT.AddMessage(WMO.UserID,msgCHO, SMS_ContentType.SMS_TEXT);
                        WMT.MsgType = SMS_MsgType.SMS_TINHTIEN;
                        WMT.Insert();
						xs_wait.InsetSMS_WAIT(WMO.MO_ID,WMO.UserID,WMO.ServiceID,WMO.CommandCode,"TD",WMO.RequestID,WMO.RequestTime,0,1);
					}
					else
					{
						string strReturnMsg = GetReturnMsg();
						if(strReturnMsg!="")
						{
							WMT.AddMessage(WMO.UserID, strReturnMsg, SMS_ContentType.SMS_TEXT);
							WMT.MsgType = SMS_MsgType.SMS_TINHTIEN;
							WMT.Insert(); 
						}
					}
				}
                else if (msg[0].Trim().ToUpper() == "CHO")//cho nhan ket qua
                {
                    string msgCHO = "7x62 xac nhan yeu cau CHO nhan ket qua XSTD cua ban.Cam on ban da su dung dich vu cua chung toi";
                    WMT.AddMessage(WMO.UserID, msgCHO, SMS_ContentType.SMS_TEXT);
                    WMT.MsgType = SMS_MsgType.SMS_TINHTIEN;
                    WMT.Insert();
                    xs_wait.InsetSMS_WAIT(WMO.MO_ID, WMO.UserID, WMO.ServiceID, WMO.CommandCode, "TD", WMO.RequestID, WMO.RequestTime, 0, 1);
                }
                else//nhan ket qua theo ngay
                {
                    string str = GetReturnMsg(msg);
                    if (string.IsNullOrEmpty(str))
                    {
                        str = "Nhan ket qua moi nhat: XSTD gui 7162.Cho nhan ket qua: XSTD CHO gui 7162.Nhan ket qua theo ngay soan: XS MaTinh NgayThang.VD: XS TD 15/09 gui 7162";
                    }
                    WMT.AddMessage(WMO.UserID, str, SMS_ContentType.SMS_TEXT);
                    WMT.MsgType = SMS_MsgType.SMS_TINHTIEN;
                    WMT.Insert();
                }
			}
				//************tuong that truc tiep
            else if ((WMO.UserID == "84978925568") || (WMO.ServiceID.Replace("04", "") == "7562") || (WMO.ServiceID.Replace("04", "") == "7662"))
			{
                string msgTT = "7x62 xac nhan yeu cau tuong thuat XSTD cua ban.Ket qua se duoc chung toi gui den ban lien tuc moi khi quay xong mot giai";
                WMT.AddMessage(WMO.UserID, msgTT, SMS_ContentType.SMS_TEXT);
                WMT.MsgType = SMS_MsgType.SMS_TINHTIEN;
                WMT.Insert();
				xs_wait.InsetSMS_WAIT(WMO.MO_ID,WMO.UserID,WMO.ServiceID,WMO.CommandCode,"TD",WMO.RequestID,WMO.RequestTime,1,8);
			}
				//************cho nhan ket qua 21 ngay lien tiep
			else if(WMO.ServiceID.Replace("04","")=="7762")
			{
                string msgCHO = "7x62 xac nhan yeu cau CHO nhan ket qua XSTD cua ban.Chung toi se gui den ban ket qua XSTD cua 30 ngay tiep theo";
                WMT.AddMessage(WMO.UserID, msgCHO, SMS_ContentType.SMS_TEXT);
                WMT.MsgType = SMS_MsgType.SMS_TINHTIEN;
                WMT.Insert();
				xs_wait.InsetSMS_WAIT(WMO.MO_ID,WMO.UserID,WMO.ServiceID,WMO.CommandCode,"TD",WMO.RequestID,WMO.RequestTime,0,21);
			}
			else
			{	
				string msgbd="Soan tin: XSTD\n";
                msgbd += "Gui 7162 de nhan kq moi nhat\n";
                msgbd += "Gui 7562 de nhan kq tuong thuat\n";
                msgbd += "Gui 7762 de nhan kq 30 ngay lien tiep\n";
                msgbd += "Chi tiet xem tai:www.7x62.vn";                
				WMT.AddMessage(WMO.UserID, msgbd, SMS_ContentType.SMS_TEXT);
				WMT.MsgType = SMS_MsgType.SMS_TINHTIEN;
				WMT.Insert(); 
			}
		}
		private string GetReturnMsg()
		{			
			string msgBody= String.Empty;			
			string connString = ConfigurationSettings.AppSettings["CONNECTION_STRING_7x62"].ToString();
			string strSQl = "SELECT TOP 1 * FROM XOSO WHERE Mamien='MB' ORDER BY Ngay DESC"	;
			SqlConnection oledbConn = new SqlConnection(connString);			
			SqlDataAdapter oleda  = new SqlDataAdapter(strSQl, oledbConn);
			DataSet ds = new DataSet();
			DataTable dt = new DataTable();				
			oledbConn.Open();// Open connection
			oleda.Fill(ds, "HANEL");
			oledbConn.Close();
			dt = ds.Tables["HANEL"];								
			DateTime dateTime = DateTime.Parse(dt.Rows[0]["Ngay"].ToString());
			if (ds.Tables[0].Rows.Count>0)
			{						
				msgBody = string.Concat("TD:",string.Concat(dateTime.Day,"/",dateTime.Month),"\n",
					"DB:",dt.Rows[0]["GiaiDacBiet"].ToString().Trim().Replace(" ",""),"\n",
					"1:",dt.Rows[0]["GiaiNhat"].ToString().Trim().Replace(" ",""),"\n",
					"2:",dt.Rows[0]["GiaiNhi"].ToString().Trim().Replace(" ",""),"\n",
					"3:",dt.Rows[0]["GiaiBa"].ToString().Trim().Replace(" ",""),"\n",
					"4:",dt.Rows[0]["GiaiTu"].ToString().Trim().Replace(" ",""),"\n",
					"5:",dt.Rows[0]["GiaiNam"].ToString().Trim().Replace(" ",""),"\n",
					"6:",dt.Rows[0]["GiaiSau"].ToString().Trim().Replace(" ",""),"\n",
					"7:",dt.Rows[0]["GiaiBay"].ToString().Trim().Replace(" ",""));
			}
			else
			{
				msgBody = ConfigSettings.ReadSetting("SMS_HELP_XS");
			}			
			ds.Dispose();
            oledbConn.Dispose();
			return msgBody;
		}
        private string GetReturnMsg(string[] arr)
        {
            #region Khai báo kết nối
            string connString = ConfigurationSettings.AppSettings["CONNECTION_STRING_7x62"].ToString();
            SqlConnection oledbConn = new SqlConnection(connString);
            string strSQl = string.Empty;
            //SqlCommand cmd = new SqlCommand();
            SqlDataAdapter oleda;// = new SqlDataAdapter();
            DataSet ds;// = new DataSet();
            DataTable dt = new DataTable();
            string code = string.Empty;
            string msgBody = string.Empty;            
            #endregion
            try
            {
                string strd = arr[0].Split('/')[0];
                string strm = arr[0].Split('/')[1];
                if (strd.Length == 1) strd = "0" + strd;
                if (strm.Length == 1) strm = "0" + strm;
                string d = strd + "/" + strm + "/" + DateTime.Now.Year.ToString();
                oledbConn.Open();
                strSQl = "SELECT TOP 1 * FROM XOSO WHERE mamien='MB' And Convert(nvarchar(10),ngay,103)='" + d + "'";
                oleda = new SqlDataAdapter(strSQl, oledbConn);
                ds = new DataSet();
                oleda.Fill(ds, "HANEL");
                dt = ds.Tables["HANEL"];
                oledbConn.Close();
                if (dt.Rows.Count > 0)
                {
                    msgBody = string.Concat(arr[0], "\n",
                    "DB:", dt.Rows[0]["GiaiDacBiet"].ToString().Trim().Replace(" ", ""), "\n",
                    "1:", dt.Rows[0]["GiaiNhat"].ToString().Trim().Replace(" ", ""), "\n",
                    "2:", dt.Rows[0]["GiaiNhi"].ToString().Trim().Replace(" ", ""), "\n",
                    "3:", dt.Rows[0]["GiaiBa"].ToString().Trim().Replace(" ", ""), "\n",
                    "4:", dt.Rows[0]["GiaiTu"].ToString().Trim().Replace(" ", ""), "\n",
                    "5:", dt.Rows[0]["GiaiNam"].ToString().Trim().Replace(" ", ""), "\n",
                    "6:", dt.Rows[0]["GiaiSau"].ToString().Trim().Replace(" ", ""), "\n",
                    "7:", dt.Rows[0]["GiaiBay"].ToString().Trim().Replace(" ", ""));
                }
                else
                {
                    msgBody = "";
                }
            }
            catch
            {
                msgBody = "Cu phan nhan tin khong hop len.De nhan kq xs mien Bac theo ngay soan tin: XSTD dd/mm gui 7162, vidu: XSTD 15/09 gui 7162";
            }
            return msgBody;
        }
        //Neu co ket qua moi va da quay xong
		private Boolean CheckCurrentResult()
		{
			Boolean val=false;
			string connString = ConfigurationSettings.AppSettings["CONNECTION_STRING_7x62"].ToString();
			string strSQl = "SELECT GIAIDACBIET FROM XOSO WHERE Mamien='MB' and convert(nvarchar(10),Ngay,103)=convert(nvarchar(10),getdate(),103)"	;
			SqlConnection oledbConn = new SqlConnection(connString);
			SqlDataAdapter oleda  = new SqlDataAdapter(strSQl, oledbConn);
			DataSet ds = new DataSet();			
			oledbConn.Open();// Open connection
			oleda.Fill(ds, "HANEL");
			oledbConn.Close();
			if((ds.Tables["HANEL"].Rows.Count>0) && (!string.IsNullOrEmpty(ds.Tables["HANEL"].Rows[0]["GIAIDACBIET"].ToString().Trim())))		
				val=true;
            ds.Dispose();
            oledbConn.Dispose();
			return val;
		}
		#endregion
	}
}
